
//
//  PhoneBindViewController.m
//  AnProject
//
//  Created by edianzu on 2017/5/18.
//  Copyright © 2017年 edianzu. All rights reserved.
//

#import "PhoneBindViewController.h"

@interface PhoneBindViewController ()
@property (nonatomic, strong) UITextField *phoneNumTextfield;//输入手机号
@property (nonatomic, strong) UITextField *identifyingTextfield;//输入验证码
@property (nonatomic, strong) UIView *line;//横线
@property (nonatomic, strong) UIView *line1;//横线
@property (nonatomic, strong) UIButton *getIdentifying;//获取验证码
@property (nonatomic, strong) UIButton *ensureBtn;//确定按钮
@property (nonatomic, strong) UIImageView *aImageView;
@property (nonatomic, strong) UILabel *label;
@end

@implementation PhoneBindViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackItem];
    self.title = @"绑定手机";
    self.view.backgroundColor = ColorWhite;
    [self addobServer];
    
    
    _aImageView = [UIImageView new];
    _aImageView.image = IMAGE(@"login_logo");
    [self.view addSubview:_aImageView];
    [_aImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(56);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.equalTo(@90);
        make.height.equalTo(@90);
    }];
    
    _label = [UILabel new];
    if(USER_TEL.length > 0)
    {
        _label.text = [NSString stringWithFormat:@"您当前的手机号为\n%@更换后可用新手机号码登录", [USER_TEL stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"]];
    }
    _label.numberOfLines = 2;
    [_label sizeToFit];
    _label.textColor = ColorFrom16(0x4a4a4a);
    _label.textAlignment = 1;
    _label.font = PFRFONT(14);
    [self.view addSubview:_label];
    [_label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_aImageView.mas_bottom).offset(32);
        make.left.equalTo(self.view).offset(30);
        make.right.equalTo(self.view).offset(-30);
        make.height.equalTo(@40);
    }];
    
    
    _phoneNumTextfield = [UITextField new];
    _phoneNumTextfield.clearButtonMode = UITextFieldViewModeWhileEditing;
    _phoneNumTextfield.placeholder = @"请输入手机号";
    _phoneNumTextfield.keyboardType = UIKeyboardTypeNumberPad;
    [_phoneNumTextfield setValue:ColorFrom16A(0x9f9f9f, 1) forKeyPath:@"_placeholderLabel.textColor"];//通过kvc去改变占位符的字体颜色
    [_phoneNumTextfield setValue:PFRFONT(15) forKeyPath:@"_placeholderLabel.font"];
    [self.view addSubview:_phoneNumTextfield];
    [_phoneNumTextfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_label.mas_bottom).offset(52);
        make.left.equalTo(self.view).offset(62);
        make.right.equalTo(self.view).offset(-62);
        make.height.equalTo(@21);
    }];
    
    _line = [UIView new];
    _line.backgroundColor = ColorFrom16(0xe2e2e2);
    [self.view addSubview:_line];
    [_line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_phoneNumTextfield.mas_bottom).offset(15);
        make.left.equalTo(self.view).offset(62);
        make.right.equalTo(self.view).offset(-62);
        make.height.equalTo(@0.5);
    }];
    
    _identifyingTextfield = [UITextField new];
    _identifyingTextfield.clearButtonMode = UITextFieldViewModeWhileEditing;
    _identifyingTextfield.placeholder = @"输入验证码";
    _identifyingTextfield.keyboardType = UIKeyboardTypeNumberPad;
    [_identifyingTextfield setValue:ColorFrom16A(0x9f9f9f, 1) forKeyPath:@"_placeholderLabel.textColor"];//通过kvc去改变占位符的字体颜色
    [_identifyingTextfield setValue:PFRFONT(15) forKeyPath:@"_placeholderLabel.font"];
    [self.view addSubview:_identifyingTextfield];
    [_identifyingTextfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_line.mas_bottom).offset(15);
        make.left.equalTo(self.view).offset(62);
        make.right.equalTo(self.view).offset(-105);
        make.height.equalTo(@21);
    }];
    
    _line1 = [UIView new];
    _line1.backgroundColor = ColorFrom16(0xe2e2e2);
    [self.view addSubview:_line1];
    [_line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_identifyingTextfield.mas_bottom).offset(15);
        make.left.equalTo(self.view).offset(62);
        make.right.equalTo(self.view).offset(-62);
        make.height.equalTo(@0.5);
    }];
    
    
    _getIdentifying = [UIButton buttonWithType:UIButtonTypeCustom];
    [_getIdentifying setTitle:@"点击获取" forState:0];
    [_getIdentifying setTitleColor:ColorFrom16(0xffffff) forState:0];
    _getIdentifying.titleLabel.font = PFRFONT(14);
    _getIdentifying.backgroundColor = ColorFrom16(0xf9bc4f);
    _getIdentifying.layer.cornerRadius = 3;
    _getIdentifying.layer.masksToBounds = YES;
    [_getIdentifying addTarget:self action:@selector(handleGetIdentifyingBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_getIdentifying];
    [_getIdentifying mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_line.mas_bottom).offset(12);
        make.right.equalTo(self.view).offset(-62);
        make.height.equalTo(@28.5);
        make.width.equalTo(@64);
    }];
    
    _ensureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_ensureBtn setTitle:@"确认" forState:UIControlStateNormal];
    _ensureBtn.layer.backgroundColor = ColorFrom16(0xFEDE6D).CGColor;
    _ensureBtn.layer.cornerRadius = 7;
    [_ensureBtn addTarget:self action:@selector(handleEnsureBtn:) forControlEvents:UIControlEventTouchUpInside];
    _ensureBtn.titleLabel.font = PFRFONT(15);
    [_ensureBtn setTitleColor:ColorFrom16(0x202020) forState:UIControlStateNormal];
    [self.view addSubview:_ensureBtn];
    [_ensureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_line1.mas_bottom).offset(31.5);
        make.left.equalTo(self.view).offset(40);
        make.right.equalTo(self.view).offset(-40);
        make.height.equalTo(@44);
    }];
    
    
}

- (void) addobServer
{
    //使用NSNotificationCenter 监听键盘出现
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShown:)
                                                 name:UIKeyboardWillChangeFrameNotification object:nil];
    //使用NSNotificationCenter 键盘隐藏时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - 确认按钮
- (void)handleEnsureBtn:(UIButton *)sender
{
    if(![_phoneNumTextfield.text isPhoneNumber])
    {
        MESSAGE_TOAST(@"请输入正确的手机号");
        return ;
    }
    if (_identifyingTextfield.text.length == 0) {
        MESSAGE_TOAST(@"请输入验证码");
        return;
    }
    
    if([self.string isEqualToString:@"微信"])
    {
        NSDictionary *param = @{@"unionid":self.unionid,
                                @"openid": self.openid,
                                @"headimgurl":self.head_url,
                                @"nickname": self.wxname,
                                @"phone": _phoneNumTextfield.text,
                                @"captcha":_identifyingTextfield.text};
        [NetWork sendPostRequestURL:[NSString stringWithFormat:@"%@/passport/login", GW_Domain] parameters:param completionBlockWithSuccess:^(NSDictionary *resultDict) {
            NSLog(@"微信绑定手机号%@", resultDict);
            [GW_Tool saveLoginInfoWithDict:resultDict[@"data"]];
            [self loginSuccessAndCloseVC];
        } andFailure:^(NSError *error, NSString *errorMsg) {
            MESSAGE_TOAST(errorMsg);
            NSLog(@"%@", error);
        }];
    }
    else
    {//个人信息
        
        [SVProgressHUD show];
        NSDictionary *param = @{@"phone":_phoneNumTextfield.text, @"captcha":_identifyingTextfield.text};
//        @weakobj(self);
        [NetWork sendPostRequestURL:[NSString stringWithFormat:@"%@/common/setPhone", GW_Domain] parameters:param completionBlockWithSuccess:^(NSDictionary *resultDict) {
            NSLog(@"%@", resultDict);
//            @strongobj(strongSelf);
            [SVProgressHUD dismiss];
            if([[NSString stringWithFormat:@"%@", resultDict[@"code"]] isEqualToString:@"0"])
            {
                [GW_Tool saveLoginInfoWithDict:resultDict[@"data"]];
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } andFailure:^(NSError *error, NSString *errorMsg) {
            MESSAGE_TOAST(errorMsg);
        }];
    }
    
}


#pragma mark - 获取验证码
- (void)handleGetIdentifyingBtn:(UIButton *)sender
{
    //正则表达式判断手机号
    if(![_phoneNumTextfield.text isPhoneNumber])
    {
        MESSAGE_TOAST(@"请输入正确的手机号");
        return ;
    }
    
    if([self.string isEqualToString:@"微信"])
    {
        [self getIdentifyingNet];
    }
    else if([self.string isEqualToString:@"个人信息"])
    {
        [self getIdentifyingNet];

    }
}

#pragma mark - 获取验证码
- (void)getIdentifyingNet
{
    [SVProgressHUD show];
    BaseNetwork *netWork = [[BaseNetwork alloc] init];
    NSDictionary *param = @{@"phone":_phoneNumTextfield.text};
    NSString *url = [NSString stringWithFormat:@"%@/common/getcode",GW_Domain];
    @weakobj(self);
    [netWork sendPostRequestURL:url parameters:param completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@"验证码成功%@", resultDict);
        @strongobj(self);
        MESSAGE_TOAST(@"验证码已发送");
        [GW_Tool getIdentifying:self.getIdentifying];
        
    } andFailure:^(NSError *error, NSString *errorMsg) {
        MESSAGE_TOAST(errorMsg);
    }];
    
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
- (void)loginSuccessAndCloseVC {
    
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        if (self.loginSuccessBlock) {
            self.loginSuccessBlock();
        }
    }];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

//键盘弹出
- (void)keyboardWillShown:(NSNotification*)aNotification
{
    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect=CGRectMake(0.0f, -56, GWIDTH, GHEIGHT);
    self.view.frame = rect;
    [UIView commitAnimations];
}
//键盘隐藏
- (void)keyboardWillBeHidden:(NSNotification *)aNotification
{
    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect=CGRectMake(0.0f, 56,GWIDTH,GHEIGHT);
    self.view.frame = rect;
    [UIView commitAnimations];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
